package com.fs.controller.v1;

import com.fs.controller.vo.PageData;
import com.fs.controller.vo.purchase.ReqAdminQueryPurchase;
import com.fs.controller.vo.purchase.RespQueryPurchase;
import com.fs.global.init.RoleName;
import com.fs.service.PurchaseService;
import com.fs.service.bo.BoPageInfo;
import com.fs.service.bo.purchase.BoPurchaseWithRoomAndCustomer;
import com.fs.service.bo.purchase.BoQueryParam;
import com.fs.service.bo.purchase.Status;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "订单管理", description = "管理员账户使用")
@RestController
@RequestMapping("/v1/purchase")
@RequiresRoles(RoleName.ADMIN)
@Validated
public class PurchaseController {

    private final PurchaseService purchaseService;

    public PurchaseController(PurchaseService purchaseService) {
        this.purchaseService = purchaseService;
    }

    @ApiOperation("订单查询")
    @GetMapping
    public PageData<RespQueryPurchase> queryPurchase(@Valid ReqAdminQueryPurchase req) {

        BoQueryParam param = new BoQueryParam();

        if (req.getRoomId() != null) {
            param.setRoomId(req.getRoomId());
        }

        if (StringUtils.hasLength(req.getCustomerName())) {
            param.setCustomerName(req.getCustomerName());
        }

        if (StringUtils.hasLength(req.getStartDate())) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate start = LocalDate.parse(req.getStartDate(), formatter);
            param.setStartDate(start);
        }
        if (StringUtils.hasLength(req.getEndDate())) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate end = LocalDate.parse(req.getEndDate(), formatter);
            param.setEndDate(end);
        }

        if (StringUtils.hasLength(req.getState())) {
            try {
                param.setState(Enum.valueOf(Status.class, req.getState()));
            } catch (IllegalArgumentException exception) {
                throw new BadRequestException("状态参数非法");
            }
        }

        BoPageInfo<BoPurchaseWithRoomAndCustomer> result = purchaseService.query(param, req.getPageNo(), req.getPageSize());
        List<RespQueryPurchase> data = result.getResults().stream().map(RespQueryPurchase::new).collect(Collectors.toList());
        return new PageData<>(data, result.getTotal());
    }

}
